#include"mystdio.h"

#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
#include <stdlib.h> // for malloc, free
#include <unistd.h> 



static MyFile * BuyFile(int fd,int flag){
  MyFile * f=(MyFile *)malloc(sizeof(MyFile));
  if(f==NULL) return NULL;
  f->bufferlen=0;
  f->fileno=fd;
  f->flag=flag;
  f->flush_method=LINE_FLUSH;
  memset(f->outbuffer,0,sizeof(f->outbuffer));
  return f;
}
// mystdio.c (MyFopen函数)
MyFile* MyFopen(const char* path, const char* mode) {
    int flag = 0;
    mode_t permissions = 0666;
    
    if(strcmp(mode, "w") == 0) {
        flag = O_CREAT | O_WRONLY | O_TRUNC;
    } 
    else if(strcmp(mode, "a") == 0) {
        flag = O_CREAT | O_WRONLY | O_APPEND;
    }
    else {
        return NULL;
    }
    
    int fd = open(path, flag, permissions);
    if(fd < 0) {
        perror("open failed"); // 添加错误诊断
        return NULL;
    }
    
    return BuyFile(fd, flag);
}

void MyFclose(MyFile * file){
  if(file->fileno <0) return ;
  MyFFlush(file);
  close(file->fileno);
  free(file);
}

int MyFwrite(MyFile * file,void * str,int len){
  //拷贝
  memcpy(file->outbuffer+file->bufferlen,str,len);
  file->bufferlen+=len;
  //尝试判断是否满足刷新条件
  if((file->flush_method&LINE_FLUSH)&&file->outbuffer[file->bufferlen-1]=='\n'){
    MyFFlush(file);
    
  }
  return 0;
}
void MyFFlush(MyFile *file){
  if(file->bufferlen<=0)return ;
  int n=write(file->fileno,file->outbuffer,file->bufferlen);
  (void)n;
  file->bufferlen=0;


}
